/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.base.web.fixedexpense;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.*;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.entity.taccount.Taccount;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.base.service.taccount.TaccountService;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 固定费用项目Controller
 * @author Kilo
 * @version 2021-03-02
 */
@Controller
@RequestMapping(value = "${adminPath}/base/fixedexpense/fixedExpense")
public class FixedExpenseController extends BaseController {

	@Autowired
	private FixedExpenseService fixedExpenseService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private TaccountService taccountService;
    @Autowired
    private UserService userService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public FixedExpense get(String fixedExpenseId, boolean isNewRecord) {
		return fixedExpenseService.get(fixedExpenseId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:view")
	@RequestMapping(value = {"list", ""})
	public String list(FixedExpense fixedExpense, Model model) {
        model.addAttribute("listUser", userService.findList(new User()));
        model.addAttribute("fixedExpense", fixedExpense);
		return "modules/base/fixedexpense/fixedExpenseList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<FixedExpense> listData(FixedExpense fixedExpense, HttpServletRequest request, HttpServletResponse response) {
		fixedExpense.setPage(new Page<>(request, response));
		Page<FixedExpense> page = fixedExpenseService.findPage(fixedExpense);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:view")
	@RequestMapping(value = "form")
	public String form(FixedExpense fixedExpense, Model model) {
		model.addAttribute("fixedExpense", fixedExpense);
		Supplier supplier = new Supplier();
		supplier.setSupplierType("1");
		List<Supplier> zifangList = supplierService.findList(supplier);
		model.addAttribute("zifangList", zifangList);
		List<Customer> customerList = customerService.findList(new Customer());
		model.addAttribute("customerList", customerList);
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList", supplierList);
		List<Taccount> taccountList=taccountService.findList(new Taccount());
		model.addAttribute("taccountList", taccountList);
        model.addAttribute("listUser", userService.findList(new User()));
        return "modules/base/fixedexpense/fixedExpenseForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:view")
	@RequestMapping(value = "detail")
	public String detail(FixedExpense fixedExpense, Model model) {
		model.addAttribute("fixedExpense", fixedExpense);
		List<Taccount> taccountList=taccountService.findList(new Taccount());
		model.addAttribute("taccountList", taccountList);
        model.addAttribute("listUser", userService.findList(new User()));
        return "modules/base/fixedexpense/fixedExpenseDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated FixedExpense fixedExpense) {

		if("1".equals(fixedExpense.getPriceMethod())){// 固定价格
			if(fixedExpense.getSalesPrice() == null){
				return renderResult(Global.FALSE, text("请填写标准销售价格！"));
			}
			if(fixedExpense.getPurchasePrice() == null){
				return renderResult(Global.FALSE, text("请填写标准采购价格！"));
			}
			if(ListUtils.isNotEmpty(fixedExpense.getCustomerPriceList())){
				for (CustomerPrice customerPrice : fixedExpense.getCustomerPriceList()) {
					if(customerPrice.getPrice() == null){
						return renderResult(Global.FALSE, text("请填写客户的销售价格！"));
					}
				}
			}
			if(ListUtils.isNotEmpty(fixedExpense.getSupplierPriceList())){
				for (SupplierPrice supplierPrice : fixedExpense.getSupplierPriceList()) {
					if(supplierPrice.getPrice() == null){
						return renderResult(Global.FALSE, text("请填写供应商的采购价格！"));
					}
				}
			}
		} else if("3".equals(fixedExpense.getPriceMethod())){// 固定比例
			if(StringUtils.isEmpty(fixedExpense.getSalesPriceRatio())){
				return renderResult(Global.FALSE, text("请填写标准销售价格比例！"));
			}
			if(StringUtils.isEmpty(fixedExpense.getPurchasePriceRatio())){
				return renderResult(Global.FALSE, text("请填写标准采购价格比例！"));
			}
			if(ListUtils.isNotEmpty(fixedExpense.getCustomerPriceList())){
				for (CustomerPrice customerPrice : fixedExpense.getCustomerPriceList()) {
					if(customerPrice.getRatio() == null){
						return renderResult(Global.FALSE, text("请填写客户的销售价格比例！"));
					}
				}
			}
			if(ListUtils.isNotEmpty(fixedExpense.getSupplierPriceList())){
				for (SupplierPrice supplierPrice : fixedExpense.getSupplierPriceList()) {
					if(supplierPrice.getRatio() == null){
						return renderResult(Global.FALSE, text("请填写供应商的采购价格比例！"));
					}
				}
			}
		}
		List<String> list1 = fixedExpense.getVehicleSettlementInfoList().stream().map(VehicleSettlementInfo::getInvestor).distinct().collect(Collectors.toList());
		if(fixedExpense.getVehicleSettlementInfoList().size() != list1.size()) {
			return renderResult(Global.FALSE, text("车辆结算信息中存在重复的资方！"));
		}

		List<String> list2 = fixedExpense.getCustomerPriceList().stream().map(CustomerPrice::getCustomerId).distinct().collect(Collectors.toList());
		if(fixedExpense.getCustomerPriceList().size() != list2.size()) {
			return renderResult(Global.FALSE, text("销售价格管理中存在重复的客户！"));
		}

		List<String> list3 = fixedExpense.getSupplierPriceList().stream().map(SupplierPrice::getSupplierId).distinct().collect(Collectors.toList());
		if(fixedExpense.getSupplierPriceList().size() != list3.size()) {
			return renderResult(Global.FALSE, text("采购价格管理中存在重复的供应商！"));
		}

		List<LadderPrice> ladderPriceList = fixedExpense.getLadderPriceList();
		Double old = 0D;
		String investorId;
		for (int i = 0; i < ladderPriceList.size(); i++) {
			if(i == 0){
				continue;
			} else {
				old = ladderPriceList.get(i-1).getEndAmount();
				investorId = ladderPriceList.get(i-1).getInvestorId();
			}
			if(ladderPriceList.get(i).getInvestorId().equals(investorId) && ladderPriceList.get(i).getStartAmount() != old + 1){
				return renderResult(Global.FALSE, text("阶梯价格起始金额必须连续！"));
			}
		}

		List<CurrencyLadderPrice> currencyLadderPriceList = fixedExpense.getCurrencyLadderPriceList();
		Double oldc = 0D;
		String currency;
		for (int i = 0; i < currencyLadderPriceList.size(); i++) {
			if(i == 0){
				continue;
			} else {
				oldc = currencyLadderPriceList.get(i-1).getEndAmount();
				currency = currencyLadderPriceList.get(i-1).getCurrencyId();
			}
			if(currencyLadderPriceList.get(i).getCurrencyId().equals(currency) && currencyLadderPriceList.get(i).getStartAmount() != oldc + 1){
				return renderResult(Global.FALSE, text("外币阶梯价格起始金额必须连续！"));
			}
		}
		fixedExpenseService.save(fixedExpense);
		return renderResult(Global.TRUE, text("保存固定费用项目成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("base:fixedexpense:fixedExpense:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(FixedExpense fixedExpense) {
		fixedExpenseService.delete(fixedExpense);
		return renderResult(Global.TRUE, text("删除固定费用项目成功！"));
	}
	
}